import type { FileUploadItem } from '../components/FileUploader/types';

import { acceptHMRUpdate, defineStore } from 'pinia';

import { formatTime } from '#/utils/time';

import { StringFormat } from '../api/file-transfer/utils';

// 单个文件项
export interface FileItem {
  id: string;
  name: string;
  size: number;
  status: 'error' | 'success' | 'uploading';
  progress?: number;
}

// 历史记录项
export interface HistoryItem {
  id: string;
  shareCode: string; // 分享码
  editToken?: string; // 编辑令牌，用于管理分享
  backendId?: number; // 后端分享记录ID
  files: FileItem[]; // 包含的文件列表
  uploadTime: number; // 改为时间戳（毫秒）
  uploadSpeed?: string;
  message?: string;
  status: 'error' | 'success' | 'uploading';
  totalSize: number; // 总大小
  totalProgress?: number; // 总进度
  expiryTime?: number; // 分享过期时间戳
}

interface UploadHistoryState {
  history: HistoryItem[];
}

/**
 * 上传历史记录 Store
 */
export const useUploadHistoryStore = defineStore('upload-history', {
  state: (): UploadHistoryState => ({
    history: [],
  }),

  getters: {
    // 获取所有历史记录（带格式化时间）
    getAllHistory: (state): (HistoryItem & { formattedTime: string })[] =>
      state.history.map((item) => ({
        ...item,
        formattedTime: formatTime(new Date(item.uploadTime)),
      })),

    // 获取统计信息
    getStats: (state) => {
      const total = state.history.length;
      const success = state.history.filter(
        (item) => item.status === 'success',
      ).length;
      const uploading = state.history.filter(
        (item) => item.status === 'uploading',
      ).length;
      const totalSize = state.history.reduce(
        (sum, item) => sum + item.totalSize,
        0,
      );
      const totalFiles = state.history.reduce(
        (sum, item) => sum + item.files.length,
        0,
      );

      return {
        total,
        success,
        uploading,
        totalSize,
        totalFiles,
      };
    },

    // 按状态筛选
    getByStatus:
      (state) =>
      (
        status: 'error' | 'success' | 'uploading',
      ): (HistoryItem & { formattedTime: string })[] => {
        return state.history
          .filter((item) => item.status === status)
          .map((item) => ({
            ...item,
            formattedTime: formatTime(new Date(item.uploadTime)),
          }));
      },

    // 根据分享码查找
    getByShareCode:
      (state) =>
      (
        shareCode: string,
      ): (HistoryItem & { formattedTime: string }) | undefined => {
        const item = state.history.find((item) => item.shareCode === shareCode);
        return item
          ? {
              ...item,
              formattedTime: formatTime(new Date(item.uploadTime)),
            }
          : undefined;
      },
  },

  actions: {
    /**
     * 添加新的上传历史记录
     */
    addHistoryItem(
      items: FileUploadItem[],
      shareCode: string,
      message?: string,
      averageSpeed?: number, // 添加平均速度参数
      editToken?: string, // 编辑令牌
      backendId?: number, // 后端分享记录ID
    ) {
      const successItems = items.filter((item) => item.status === 'success');

      if (successItems.length > 0) {
        // 计算实际上传速度，如果没有提供则使用默认值
        const uploadSpeed = averageSpeed
          ? StringFormat.formatSpeed(averageSpeed)
          : '-- MB/s';

        const historyItem: HistoryItem = {
          id: `history-${Date.now()}`,
          shareCode,
          editToken, // 存储编辑令牌
          backendId, // 存储后端ID
          files: successItems.map((item) => ({
            id: item.uploadedId || item.id,
            name: item.name,
            size: item.size,
            status: 'success',
          })),
          uploadTime: Date.now(), // 存储时间戳
          uploadSpeed, // 使用计算的上传速度
          message,
          status: 'success',
          totalSize: successItems.reduce((sum, item) => sum + item.size, 0),
        };

        // 添加到历史记录顶部
        this.history.unshift(historyItem);
      }
    },

    /**
     * 更新历史记录项
     */
    updateHistoryItem(id: string, updates: Partial<HistoryItem>) {
      const index = this.history.findIndex((item) => item.id === id);
      if (index !== -1) {
        const currentItem = this.history[index];
        if (currentItem) {
          this.history[index] = {
            id: currentItem.id,
            shareCode: updates.shareCode ?? currentItem.shareCode,
            files: updates.files ?? currentItem.files,
            uploadTime: updates.uploadTime ?? currentItem.uploadTime,
            uploadSpeed: updates.uploadSpeed ?? currentItem.uploadSpeed,
            message: updates.message ?? currentItem.message,
            status: updates.status ?? currentItem.status,
            totalSize: updates.totalSize ?? currentItem.totalSize,
            totalProgress: updates.totalProgress ?? currentItem.totalProgress,
          };
        }
      }
    },

    /**
     * 删除历史记录项
     */
    removeHistoryItem(id: string) {
      const index = this.history.findIndex((item) => item.id === id);
      if (index !== -1) {
        this.history.splice(index, 1);
      }
    },

    /**
     * 清空所有历史记录
     */
    clearHistory() {
      this.history = [];
    },

    /**
     * 生成分享码
     */
    generateShareCode(): string {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      let result = '';
      for (let i = 0; i < 6; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return result;
    },

    /**
     * 初始化示例数据（开发用）
     */
    initSampleData() {
      if (this.history.length === 0) {
        this.history = [];
      }
    },
  },

  // 持久化配置
  persist: {
    key: 'upload-history',
    storage: localStorage,
    pick: ['history'], // 只持久化 history 字段
  },
});

// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
  hot.accept(acceptHMRUpdate(useUploadHistoryStore, hot));
}
